package com.okq.util.security;

import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 描述 : 决策器，决定某个用户具有的角色，是否有足够的权限去访问某个资源
 * 作者 : zdl
 * 日期 : 2017/3/15 13:26
 */
public class AccessDecision implements AccessDecisionManager {

	/**
	 * 日志
	 */
	private static final Logger logger = Logger.getLogger(AccessDecision.class);

	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (authentication == null || object == null || configAttributes == null) {
			throw new AccessDeniedException("没有权限");
		} else {
			if (configAttributes.size() == 0) {
				if (logger.isDebugEnabled()) {
					logger.debug("资源没有对应的角色！");
				}
				throw new AccessDeniedException("没有权限");
			}
			logger.debug("正在访问的url是：" + object.toString());
			for (ConfigAttribute ca : configAttributes) {
				String needRole = ca.getAttribute();
				for (GrantedAuthority ga : authentication.getAuthorities()) {
					logger.debug("授权信息是：" + ga.getAuthority());
					if (needRole.equals(ga.getAuthority())) {
						if (logger.isDebugEnabled()) {
							logger.debug("判断到，needRole 是" + needRole + ",用户的角色是:" + ga.getAuthority() + "，授权数据相匹配");
						}
						return;
					}
				}
			}
			throw new AccessDeniedException("没有权限");
		}
	}

	@Override
	public boolean supports(ConfigAttribute arg0) {
		return true;
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

}
